var app = getApp();
var WxParse = require('../../wxParse/wxParse.js');
Page({
  data: {
    imgUrls: [
      'https://tyc-bj.cn/yc/api/attach/images/shop-goods-details-1.jpg',
      'https://tyc-bj.cn/yc/api/attach/images/shop-goods-details-1.jpg',
      'https://tyc-bj.cn/yc/api/attach/images/shop-goods-details-1.jpg'
    ],
    //是否采用衔接滑动  
    circular: true,
    //是否显示画板指示点  
    indicatorDots: true,
    //选中点的颜色  
    indicatorcolor: "#000",
    //是否竖直  
    vertical: false,
    //是否自动切换  
    autoplay: true,
    //自动切换的间隔
    interval: 2500,
    //滑动动画时长毫秒  
    duration: 100,
    //所有图片的高度  （必须）
    imgheights: [],
    //图片宽度 
    imgwidth: 750,
    //默认  （必须）
    current: 0,
    currentTab: 0,
    info: [],
    goodsId: 0,
    goodsDetailsHtml: '',
    imgUrl: 'https://tyc-bj.cn/yc/api/attach/',
    goodsid: "", //商品ID
    goodsnum: 1, //商品数量
    etype: 1, //商品类型；1=术前术后产品，2=服务类产品，默认1
    take: !0,
    options: "",

  },
  consult: function() {
    var that = this;
    var isLogin = wx.getStorageSync('isLogin');
    const {
      info
    } = this.data;
    if (isLogin != 2) {
      wx.navigateTo({
        url: `/pages/user-my-kf/user-my-kf?doctorId=${info.doctor.userId}`,
      });
    } else {
      wx.redirectTo({
        url: '/pages/user-login/user-login',
      });
    }
  },
  // 加入购物车
  addCart: function(e) {
    const that = this;
    var stock = that.data.stock;
    if (stock <= 0) {
      wx.showToast({
        title: '商品已经售完！',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    const param = {
      goodsid: this.data.goodsid,
      goodsnum: this.data.goodsnum,
      type: 1,
    };
    app.request({
      url: 'shopp/shoppcartApi/cartAddGoods',
      data: param,
      success: function(res) {
        console.log(res)
        if (res.status_code == 200) {
          wx.showToast({
            title: '加入购物车成功',
            icon: 'success',
            duration: 1000
          })
          setTimeout(function() {
            wx.navigateTo({
              url: '../user-my-cart/user-my-cart?id=' + that.data.goodsid,
            })
          }, 1000)
        }
      },

      fail: function(res) {
        // app.requestFail(res);
      }

    });
  },

  imageLoad: function(e) {
    //获取图片真实宽度
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比
      ratio = imgwidth / imgheight;

    //计算的高度值
    var viewHeight = 750 / ratio;
    var imgheight = viewHeight
    var imgheights = this.data.imgheights
    //把每一张图片的高度记录到数组里
    imgheights.push(imgheight)
    this.setData({
      imgheights: imgheights,
    })
  },

  bindchange: function(e) {
    this.setData({
      current: e.detail.current
    })
  },

  onLoad: function(options) {
    // 页面初始化 options为页面跳转所带来的参数
    console.log('商品详情页参数:', options);

    this.loadData(options);
    if (options.image) {
      this.setData({
        image: options.image,
        roleType: wx.getStorageSync('roleType'),
        etype: options.etype,

      })
    }
    this.setData({
      options: options,
    })
  },

  // 加载数据
  loadData: function(options) {
    
    if (options.etype == 2) {
      this.setData({
        'etype': options.etype,
        'url': app.globalData.imgUrl
      })
      var that = this;
      var url = '';
      console.log('商品参数:', options)
      
      this.setData({
        goodsid: options.id,
        etype: options.etype,
      })
      if (options.etype == 1) {
        url = app.globalData.baseUrl + 'shopp/yimeiGoodsApi/getDetail/';
      } else {
        url = app.globalData.baseUrl + 'shopp/goodsApi/goodsDetail/';
      }
      wx.request({
        url: url + options.id,
        header: {
          'sign': app.globalData.sign,
          'token': app.globalData.token,
          'content-type': 'application/json'
        },
        method: 'GET',
        success(res) {
          console.log('商品详情', res.data.data);
          
          
          if (res.data.status_code == 200) {
            console.log('详情2', res.data.data.goodsDetail.ifCollection);
            if (res.data.data.goodsDetail.ifCollection == 0) {
              that.setData({
                take: !0
              })
            } else {
              that.setData({
                take: !1
              })
            }
            that.setData({
              info: res.data.data,
              goodsId: options.id,
              stock: res.data.data.goodsDetail.stock
            })
          }
        }
      })
    } else {
      this.setData({
        'etype': options.etype,
        'url': app.globalData.imgUrl
      });
      var longitude = wx.getStorageSync('longitude');
      console.log('经度:', longitude);

      var latitude = wx.getStorageSync('latitude');
      var lngandlat = longitude + ',' + latitude;
      console.log('纬度:', latitude);

      console.log('经纬度:', lngandlat);
      var that = this;
      var url = '';
      console.log('商品参数:', options)
      this.setData({
        goodsid: options.id
      })
      if (options.etype == 1) {
        url = app.globalData.baseUrl + 'shopp/yimeiGoodsApi/getDetail/';
      } else {
        url = app.globalData.baseUrl + 'shopp/goodsApi/goodsDetail/';
      }
      console.log('url:', url + options.id + '?lngandlat=' + lngandlat);

      wx.request({
        url: url + options.id + '?lngandlat=' + lngandlat,
        header: {
          'sign': app.globalData.sign,
          'token': app.globalData.token,
          'content-type': 'application/json',
        },
        method: 'GET',
        success(res) {
          console.log('商品详情', res.data.data);
          if (res.data.status_code == 200) {
            console.log('详情1', res.data.data.goodsDetail.ifCollection);
            console.log('详情1', res.data.data);
            if (res.data.data.goodsDetail.ifCollection == 0) {
              that.setData({
                take: !0
              })
            } else {
              that.setData({
                take: !1
              })
            }
            that.setData({
              doctorId: res.data.data.doctor.userId,
              info: res.data.data,
              goodsId: options.id,
            })
          }
        }
      })
    }
  },

  //滑动切换
  swiperTab: function(e) {
    var that = this;
    that.setData({
      currentTab: e.detail.current
    });
  },
  //点击切换
  clickTab: function(e) {
    var that = this;
    if (this.data.currentTab == e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
      if (e.target.dataset.current == 1) {
        that.loadDetail();
      }
    }
  },

  loadDetail: function(e) {
    var goodsId = this.data.goodsId;
    var that = this;
    var etype = this.data.etype;
    var url = '';
    if (etype == 1) {
      url = app.globalData.baseUrl + 'shopp/yimeiGoodsApi/getGoodsDetailsHtml/' + goodsId;
    } else {
      url = app.globalData.baseUrl + 'shopp/goodsApi/getGoodsDetailsHtml/' + goodsId;
    }
    console.log('详情url:', url);
    wx.request({
      url: url,
      header: {
        'sign': app.globalData.sign,
        'token': app.globalData.token,
        'content-type': 'application/json'
      },
      success(res) {
        console.log('详情html:', res);
        var detail = String(res.data);
        if (res.statusCode == 200) {
          that.setData({
            goodsDetailsHtml: res.data,
          })
          WxParse.wxParse('detail', 'html', detail, that, 5);
        }
      }
    })
  },
  //立刻购买
  buy() {
    var that = this;
    var isLogin = wx.getStorageSync('isLogin');
    console.log('是否登录:', isLogin);
    if (isLogin == 2 || !isLogin) {
      wx.showToast({
        title: '请登录!',
        icon: 'loading',
      })
      // 跳转到登入界面
      wx.redirectTo({
        url: '/pages/user-login/user-login',
      });
    } else {
      var stock = that.data.stock;
      if (stock <= 0) {
        wx.showToast({
          title: '商品已经售完！',
          icon: 'none',
          duration: 2000
        })
        return false;
      }
      if (that.data.etype == 1) {
        wx.navigateTo({
          url: "../user-shop-goods-order-medical/user-shop-goods-order-medical?id=" + this.data.goodsid + "&type=" + that.data.etype,
        })
      } else if (that.data.etype == 2) {
        let cartgoods = [];
        let item = {};
        item.goodsid = this.data.goodsid;
        item.goodsType = this.data.info.goodsDetail.goodsType;
        item.num = 1;
        cartgoods.push(item)
        const carts = JSON.stringify(cartgoods);
        console.log("carts", carts);
        wx.navigateTo({
          url: "../user-shop-goods-order-1/user-shop-goods-order-1?carts=" + carts,
        })
      }
    }
  },

  //点击收藏
  collection: function() {
    var that = this;
    console.log('cid', that.data.goodsid)
    console.log('cetype', that.data.etype)
    var cetype = that.data.etype;
    if (cetype == 1) {
      wx.request({
        url: app.globalData.baseUrl + 'doctor/member/collectGoods', //仅为示例，并非真实的接口地址
        data: {
          userId: wx.getStorageSync('userid'),
          goodsId: that.data.goodsid,
          goodsType: 2,
        },
        method: 'POST',
        header: {
          'sign': app.globalData.sign,
          'token': app.globalData.token,
          'content-type': 'application/x-www-form-urlencoded;charset=utf-8', // 默认值
        },
        success(res) {
          console.log("收藏结果", res.data)
          if (res.data.status_code == 200) {
            that.setData({
              take: !that.data.take
            })
            wx.showToast({
              title: res.data.message,
              icon: 'success',
              duration: 1000
            })
          }
        }
      })
    } else {
      wx.request({
        url: app.globalData.baseUrl + 'doctor/member/collectGoods', //仅为示例，并非真实的接口地址
        data: {
          userId: wx.getStorageSync('userid'),
          goodsId: that.data.goodsid,
          goodsType: 1,
        },
        method: 'POST',
        header: {
          'sign': app.globalData.sign,
          'token': app.globalData.token,
          'content-type': 'application/x-www-form-urlencoded;charset=utf-8', // 默认值
        },
        success(res) {
          console.log("收藏结果", res.data)
          if (res.data.status_code == 200) {
            that.setData({
              take: !that.data.take
            })
            wx.showToast({
              title: res.data.message,
              icon: 'success',
              duration: 1000
            })
          }
        }
      })
    }

  },

  // 分享
  onShareAppMessage: function() {
    return {
      title: '分享好友获取美丽币！',
      path: '/pages/index/index',
      // imageUrl: '/pages/images/aa.jpg',
      success: function() {
        wx.request({
          url: app.globalData.baseUrl + 'doctor/memberTaskApi/addBeauty',
          data: {
            userId: wx.getStorageSync('userid'),
            type: 3
          },
          header: {
            'sign': app.globalData.sign,
            'token': app.globalData.token,
            'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
          },
          method: 'POST',
          success(res) {
            console.log('分享给美丽币给美丽值', res);
          }
        })
      }
    }
  },
  //图片放大
  imgYu: function (event) {
    console.log('assacsa', event.currentTarget.dataset)
    var src = event.currentTarget.dataset.src; //获取data-src
    var imgList = event.currentTarget.dataset.list; //获取data-list
    console.log('imgList', imgList[1])
    var imgUrl = app.globalData.imgUrl;
    var a = [];
    //获取下标
    var o = event.currentTarget.dataset.inde;
    // 循环 list数组
    for (var s in imgList) a.push(imgUrl + imgList[s]);
    // a.push(imgUrl + imgLists);
    //图片预览
    console.log('yaokan1', imgUrl + imgList[o]);
    console.log('yaokan2', a);
    wx.previewImage({
      current: imgUrl + imgList[o], // 当前显示图片的http链接
      urls: a// 需要预览的图片http链接列表
    })
  },

})